package com.chao.yyks.modular.hearing.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chao.common.util.DateUtile;
import com.chao.common.util.ListUtile;
import com.chao.common.util.RequestUtile;
import com.chao.common.util.StrUtile;
import com.chao.common.util.exception.SysException;
import com.chao.common.util.file.FileUpload;
import com.chao.common.util.reaction.PageList;
import com.chao.yyks.modular.config.service.FdfsService;
import com.chao.yyks.modular.hearing.bean.EnHearing;
import com.chao.yyks.modular.hearing.mapper.EnHearingMapper;
import com.chao.yyks.modular.hearing.service.EnHearingService;
import com.chao.yyks.modular.problem.bean.EnProblem;
import com.chao.yyks.modular.problem.mapper.EnProblemAnswerMapper;
import com.chao.yyks.modular.problem.mapper.EnProblemMapper;
import com.chao.yyks.modular.score.bean.EnAnswer;
import com.chao.yyks.modular.score.bean.EnScore;
import com.chao.yyks.modular.score.mapper.EnAnswerMapper;
import com.chao.yyks.modular.score.mapper.EnScoreMapper;
import com.chao.yyks.modular.sys.bean.EnClasssType;
import com.chao.yyks.modular.sys.bean.EnStudent;
import com.chao.yyks.modular.sys.mapper.EnClasssTypeMapper;
import com.chao.yyks.modular.sys.mapper.EnStudentMapper;
import com.chao.yyks.util.Tts2File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 听力ServiceImpl
 * chao
 * 2024-09-12
 */
@Service
public class EnHearingServiceImpl implements EnHearingService {

	/**
	 * 听力Mapper
	 */
	@Autowired
	private EnHearingMapper enHearingMapper;

	/**
	 * 问题数量配置Mapper
	 */
	@Autowired
	private EnClasssTypeMapper enClasssTypeMapper;

	/**
	 * 学生Mapper
	 */
	@Autowired
	private EnStudentMapper enStudentMapper;

	/**
	 * 成绩Mapper
	 */
	@Autowired
	private EnScoreMapper enScoreMapper;

	/**
	 * 成绩答题Mapper
	 */
	@Autowired
	private EnAnswerMapper enAnswerMapper;

	/**
	 * 题库Mapper
	 */
	@Autowired
	private EnProblemMapper enProblemMapper;

	@Autowired
	private FdfsService fdfsService;

	/**
	 * 问题答案Mapper
	 */
	@Autowired
	private EnProblemAnswerMapper enProblemAnswerMapper;

	/**
	 * 新增听力
	 */
	@Override
	@Transactional
	public void insertEnHearing(EnHearing enHearing){
		if(!ListUtile.isEmpty(enHearing.getHearingList())){
			List<EnHearing> hearingList = enHearing.getHearingList();
			String uId = StrUtile.getId();
			for (EnHearing hearing:hearingList){
				hearing.setUpHearingId(uId);
				hearing.setHearingId(StrUtile.getId());
				hearing.setHearingType("1");
				hearing.setHearingDialogue("2");
				hearing.setAnnouncer(enHearing.getAnnouncer());
				hearing.setHearingSection(enHearing.getHearingSection());
				hearing.setHearingDirections(enHearing.getHearingDirections());
				hearing.setProblemDate(enHearing.getProblemDate());
				hearing.setProblemUpType(enHearing.getProblemUpType());
			}
			enHearingMapper.insertAllEnHearing(hearingList);
			return;
		}
		enHearing.setHearingId(StrUtile.getId());
		enHearing.setUpHearingId(StrUtile.getId());
		enHearing.setCtime(new Date());
		enHearingMapper.insertEnHearing(enHearing);
	}

	/**
	 * 修改听力
	 */
	@Override
	@Transactional
	public void updateEnHearing(EnHearing enHearing){
		EnHearing enHearingPojo = enHearingMapper.selectEnHearingByHearingId(enHearing.getHearingId());
		if(null == enHearingPojo){
		    throw new SysException("修改听力失败:记录不存在!");
		}
		enHearingMapper.updateEnHearing(enHearing);
	}

	/**
	 * 修改听力
	 */
	@Override
	@Transactional
	public void updateEnHearingUrl(String hearingId){
		EnHearing enHearing = enHearingMapper.selectEnHearingByHearingId(hearingId);
		if(null == enHearing){
			throw new SysException("记录不存在!");
		}
		File file = Tts2File.toFileWas(enHearing.getAnnouncer(),enHearing.getHearingTitle());
		if(file.exists()){
			FileUpload fileUpload = fdfsService.uploadThisFile(file);
			String url = fileUpload.getFilePrefix()+fileUpload.getFileUrl();
			if(StrUtile.isEmpty(fileUpload.getFileUrl())){
				throw new SysException("语音文件生成失败!");
			}
			enHearing.setHearingUrl(url);
			enHearingMapper.updateEnHearingUrl(enHearing);
			file.delete();
		}
	}

	/**
	 * 修改听力
	 */
	@Override
	@Transactional
	public void updateEnHearingThUrl(EnHearing enHearing){
		if(StrUtile.isEmpty(enHearing.getHearingId())){
			throw new SysException("请选择音频文件!");
		}
		if(StrUtile.isEmpty(enHearing.getHearingUrl())){
			throw new SysException("请先上传文件!");
		}
		enHearingMapper.updateEnHearingUrl(enHearing);
	}

	/**
	 * 物理删除听力
	 */
	@Override
	@Transactional
	public void deleteDataEnHearing(String hearingId){
		EnHearing enHearing = enHearingMapper.selectEnHearingByHearingId(hearingId);
		if(null == enHearing){
		    throw new SysException("删除听力失败:记录不存在!");
		}
		enHearingMapper.deleteDataEnHearing(enHearing.getUpHearingId());
		enHearingMapper.deleteDataEnHearing(enHearing.getHearingId());

		enProblemMapper.deleteDataEnProblem(enHearing.getUpHearingId());

		enProblemAnswerMapper.deleteDataEnProblem();

		enProblemAnswerMapper.deleteOpDataEnProblem();
	}

	/**
	 * 查询听力详情
	 */
	@Override
	public EnHearing selectEnHearingByHearingId(String hearingId){
		EnHearing enHearing = enHearingMapper.selectEnHearingByHearingId(hearingId);
		if(null == enHearing){
			throw new SysException("记录不存在!");
		}
		if("1".equals(enHearing.getHearingDialogue())){
			enHearing.setHearingList(enHearingMapper.selectEnHearingByList(JSONObject.parseObject("{\"upHearingId\":\""+enHearing.getUpHearingId()+"\"}")).getList());
		}else {
			enHearing.setHearingList(enHearingMapper.selectEnHearingByList(JSONObject.parseObject("{\"upHearingId\":\""+enHearing.getHearingId()+"\"}")).getList());
		}
		enHearing.setProblemList(enProblemMapper.selectEnProblemByEnAnswerList(JSONObject.parseObject("{\"hearingId\":\""+enHearing.getUpHearingId()+"\"}")));
		return enHearing;
	}

	/**
	 * 查询听力列表
	 */
	@Override
	public PageList<EnHearing> selectEnHearingByList(JSONObject json){
		json.put("selectList","1");
		return enHearingMapper.selectEnHearingByList(json);
	}

	/**
	 * 分页查询听力列表
	 */
	@Override
	public PageList<EnHearing> selectEnHearingByPage(JSONObject json){
		json.put("selectList","1");
		return enHearingMapper.selectEnHearingByList(StrUtile.getPageJson(json));
	}

	public static void main(String[] args) {
		System.out.println("文件有如下：");
		//表示一个文件路径
		File file = new File("C:\\Users\\chao\\Desktop\\新建文件夹 (1)");
		//用数组把文件夹下的文件存起来
		File[] files = file.listFiles();
		List<String> s = new ArrayList<>();
		//foreach遍历数组
		for (File file2 : files) {
			//打印文件列表：只读取名称使用getName();
//			System.out.println("路径："+file2.getPath());
			System.out.println("https://service.sdkjf.cn/group1/default/20241027/"+file2.getName());
			s.add("'https://service.sdkjf.cn/group1/default/20241027/"+file2.getName()+"'");
		}
		System.out.println(String.join(",", s));
	}

	/**
	 * 口语题试卷
	 */
	@Override
	public List<EnHearing> selectEnHearingKy(JSONObject json){
		if(json.containsKey("scoreId")){
			json.put("problemUpType","4");
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+json.getString("scoreId")+"\"}")).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getHearingId));
			json.put("labelId",answerList.get(0).getLabelId());
			List<EnHearing> listHearing = enHearingMapper.selectEnHearingByList(json).getList();
			List<EnHearing> listData = new ArrayList<>();
			for (EnHearing h:listHearing) {
				if(upType.containsKey(h.getHearingId())){
					h.setProblemList(upType.get(h.getHearingId()));
					listData.add(h);
				}
			}
			listData = listData.stream().sorted(Comparator.comparing(EnHearing::getHearingId)).collect(Collectors.toList());
			return listData;
		}
		if(!json.containsKey("labelId")){
			throw new SysException("请选择板块!");
		}
		json.put("problemDateThis", DateUtile.laseWook());
		json.put("problemUpType","4");
		EnStudent enStudent = enStudentMapper.selectEnStudentByStudentId(RequestUtile.getLoginUserId());
		if(null == enStudent){
			throw new SysException("登录账号异常,请重新登录或联系老师!");
		}
		List<EnClasssType> typeList = enClasssTypeMapper.selectEnClasssTypeByList(enStudent.getClasssId());
		Map<String,Integer> typeMap = typeList.stream().filter(t->"4".equals(t.getProblemUpType())).collect(Collectors.toMap(EnClasssType::getProblemType,EnClasssType::getProblemNum));
		if(typeMap.isEmpty()){
			throw new SysException("当前学生不需要填写口语题!");
		}
		json.put("studentId",enStudent.getStudentId());
		List<EnScore> scores = enScoreMapper.selectEnScoreByList(json).getList();
		if(!ListUtile.isEmpty(scores)){
			throw new SysException("当前板块本周已完成口语题,请不要重复答题!");
		}
		List<EnScore> scoreList = enScoreMapper.selectEnScoreByList(JSONObject.parseObject("{\"scoreState\":\"1\",\"studentId\":\""+enStudent.getStudentId()+"\"}")).getList();
		if(!ListUtile.isEmpty(scoreList) && (!"4".equals(scoreList.get(0).getProblemUpType()) || !scoreList.get(0).getLabelId().equals(json.getString("labelId")))){
			throw new SysException("当前有未完成的其他练习,请先完成!");
		}

		// 如果有未答完的题目 则查询继续
		if(!ListUtile.isEmpty(scoreList)){
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+scoreList.get(0).getScoreId()+"\"}")).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getHearingId));
			JSONObject da = new JSONObject();
			da.put("problemUpType","4");
			da.put("problemDate",scoreList.get(0).getProblemDate());
			List<EnHearing> listHearing = enHearingMapper.selectEnHearingByList(da).getList();
			List<EnHearing> listData = new ArrayList<>();
			for (EnHearing h:listHearing) {
				if(upType.containsKey(h.getHearingId())){
					h.setProblemList(upType.get(h.getHearingId()));
					listData.add(h);
				}
			}
			listData = listData.stream().sorted(Comparator.comparing(EnHearing::getHearingId)).collect(Collectors.toList());
			return listData;
		}
		EnScore score = new EnScore();
		score.setScoreId(StrUtile.getId());
		score.setScoreState("1");
		score.setLabelId(json.getString("labelId"));
		score.setProblemUpType("4");
		score.setStudentId(RequestUtile.getLoginUserId());

		List<EnAnswer> answerList = new ArrayList<>();
		Map<String,Integer> typeTMap = new HashMap<>();
		List<EnProblem> listProblem = enProblemMapper.selectEnProblemByList(json).getList();
		Map<String,List<EnProblem>> hearingMap = listProblem.stream().collect(Collectors.groupingBy(EnProblem::getHearingId));
		List<EnHearing> listHearing = enHearingMapper.selectEnHearingByList(json).getList();
		List<EnHearing> listData = new ArrayList<>();
		// 打乱顺序
		Collections.shuffle(listHearing);
		for (EnHearing h:listHearing) {
			h.setProblemList(new ArrayList<>());
			if(hearingMap.containsKey(h.getHearingId())){
				List<EnProblem> problemList = hearingMap.get(h.getHearingId());
				// 打乱顺序
				Collections.shuffle(problemList);
				for (EnProblem problem:problemList){
					String type = problem.getProblemType();
					if(typeMap.containsKey(type) && typeMap.get(type) > typeTMap.getOrDefault(type,0)){
						EnAnswer answer = JSONObject.parseObject(JSONObject.toJSONString(problem),EnAnswer.class);
						answer.setScoreId(score.getScoreId());
						answerList.add(answer);
						h.getProblemList().add(answer);
						typeTMap.put(type,typeTMap.getOrDefault(type,0)+1);
					}
				}
				if(!h.getProblemList().isEmpty()){
					h.setProblemList(h.getProblemList().stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList()));
					listData.add(h);
				}
			}
		}
		if(answerList.isEmpty()){
			throw new SysException("题库中未找到合适的试题,请联系老师!");
		}
		score.setProblemDate(answerList.get(0).getProblemDate());
		score.setProblemDifficulty(answerList.get(0).getProblemDifficulty());
		enAnswerMapper.insertAllEnAnswer(answerList);
		enScoreMapper.insertEnScore(score);

		listData = listData.stream().sorted(Comparator.comparing(EnHearing::getHearingId)).collect(Collectors.toList());
		return listData;
	}

	/**
	 * 听力题试卷
	 */
	@Override
	public List<JSONObject> selectEnHearing(JSONObject json){
		if(json.containsKey("scoreId")){
			json.put("problemUpType","1");
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+json.getString("scoreId")+"\"}")).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getHearingId));
			json.put("labelId",answerList.get(0).getLabelId());
			List<EnHearing> listHearing = enHearingMapper.selectEnHearingByList(json).getList();
			Map<String,List<EnHearing>> hearingMap = listHearing.stream().filter(e->!StrUtile.isEmpty(e.getHearingSection())).collect(Collectors.groupingBy(EnHearing::getHearingSection));
			Map<String,List<EnHearing>> hearingIdMap = listHearing.stream().collect(Collectors.groupingBy(EnHearing::getUpHearingId));
			List<JSONObject> listData = new ArrayList<>();
			for (Map.Entry<String,List<EnHearing>> e:hearingMap.entrySet()) {
				JSONObject j = new JSONObject();
				j.put("hearingSection",e.getKey());
				j.put("hearingDirections",e.getValue().get(0).getHearingDirections());
				Set<EnAnswer> answerSet = new HashSet<>();
				Set<String> ss = new HashSet<>();
				for (EnHearing h:e.getValue()) {
					if(upType.containsKey(h.getUpHearingId())){
						answerSet.addAll(upType.get(h.getUpHearingId()));
						ss.add(h.getUpHearingId());
					}
				}
				if(!ss.isEmpty()){
					List<EnHearing> hh = new ArrayList<>();
					for (String upId:ss) {
						List<EnHearing> hhs = hearingIdMap.get(upId);
						for (EnHearing h : hhs){
							if(hearingIdMap.containsKey(h.getHearingId())){
								h.setHearingList(hearingIdMap.get(h.getHearingId()));
							}
							hh.add(h);
						}
					}
					j.put("hearingList",hh.stream().sorted(Comparator.comparing(EnHearing::getHearingSection).thenComparing(EnHearing::getHearingId, Comparator.naturalOrder())).collect(Collectors.toList()));
					j.put("problemList",new ArrayList<>(answerSet).stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList()));
					listData.add(j);
				}
			}
			listData = listData.stream().sorted(Comparator.comparing(j -> j.getString("hearingSection"))).collect(Collectors.toList());
			return listData;
		}
		if(!json.containsKey("problemDifficulty")){
			throw new SysException("听力题请指定难度!");
		}
		json.put("problemDateThis",DateUtile.laseWook());
		json.put("problemUpType","1");
		json.put("hearingType","1");
		EnStudent enStudent = enStudentMapper.selectEnStudentByStudentId(RequestUtile.getLoginUserId());
		if(null == enStudent){
			throw new SysException("登录账号异常,请重新登录或联系老师!");
		}
		List<EnClasssType> typeList = enClasssTypeMapper.selectEnClasssTypeByList(enStudent.getClasssId());
		Map<String,Integer> typeMap = typeList.stream().filter(t->"1".equals(t.getProblemUpType())).collect(Collectors.toMap(EnClasssType::getProblemType,EnClasssType::getProblemNum));
		if(typeMap.isEmpty()){
			throw new SysException("当前学生不需要填写听力题!");
		}
		json.put("studentId",enStudent.getStudentId());
		List<EnScore> scores = enScoreMapper.selectEnScoreByList(json).getList();
		if(!ListUtile.isEmpty(scores)){
			throw new SysException("当前板块本周已完成听力题,请不要重复答题!");
		}
		List<EnScore> scoreList = enScoreMapper.selectEnScoreByList(JSONObject.parseObject("{\"scoreState\":\"1\",\"studentId\":\""+enStudent.getStudentId()+"\"}")).getList();
		if(!ListUtile.isEmpty(scoreList) && (!"1".equals(scoreList.get(0).getProblemUpType()) || !scoreList.get(0).getLabelId().equals(json.getString("labelId")))){
			throw new SysException("当前有未完成的其他练习,请先完成!");
		}

		// 如果有未答完的题目 则查询继续
		if(!ListUtile.isEmpty(scoreList)){
			List<EnAnswer> answerList = enAnswerMapper.selectEnAnswerByList(JSONObject.parseObject("{\"scoreId\":\""+scoreList.get(0).getScoreId()+"\"}")).getList();
			Map<String,List<EnAnswer>> upType = answerList.stream().collect(Collectors.groupingBy(EnAnswer::getHearingId));
			JSONObject da = new JSONObject();
			da.put("problemUpType","1");
			da.put("labelId",answerList.get(0).getLabelId());
			da.put("problemDate",scoreList.get(0).getProblemDate());
			List<EnHearing> listHearing = enHearingMapper.selectEnHearingByList(da).getList();
			Map<String,List<EnHearing>> hearingMap = listHearing.stream().filter(e->!StrUtile.isEmpty(e.getHearingSection())).collect(Collectors.groupingBy(EnHearing::getHearingSection));
			Map<String,List<EnHearing>> hearingIdMap = listHearing.stream().collect(Collectors.groupingBy(EnHearing::getUpHearingId));
			List<JSONObject> listData = new ArrayList<>();
			for (Map.Entry<String,List<EnHearing>> e:hearingMap.entrySet()) {
				JSONObject j = new JSONObject();
				j.put("hearingSection",e.getKey());
				j.put("hearingDirections",e.getValue().get(0).getHearingDirections());
				Set<EnAnswer> answerSet = new HashSet<>();
				Set<String> ss = new HashSet<>();
				for (EnHearing h:e.getValue()) {
					if(upType.containsKey(h.getUpHearingId())){
						answerSet.addAll(upType.get(h.getUpHearingId()));
						ss.add(h.getUpHearingId());
					}
				}
				if(!ss.isEmpty()){
					List<EnHearing> hh = new ArrayList<>();
					for (String upId:ss) {
						hh.addAll(hearingIdMap.get(upId));
					}
					j.put("hearingList",hh.stream().sorted(Comparator.comparing(EnHearing::getHearingSection).thenComparing(EnHearing::getHearingId, Comparator.naturalOrder())).collect(Collectors.toList()));
					j.put("problemList",new ArrayList<>(answerSet).stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList()));
					listData.add(j);
				}
			}
			listData = listData.stream().sorted(Comparator.comparing(j -> j.getString("hearingSection"))).collect(Collectors.toList());
			return listData;
		}
		EnScore score = new EnScore();
		score.setScoreId(StrUtile.getId());
		score.setScoreState("1");
		score.setLabelId(json.getString("labelId"));
		score.setProblemUpType("1");
		score.setProblemDifficulty(json.getString("problemDifficulty"));
		score.setStudentId(RequestUtile.getLoginUserId());

		List<EnAnswer> answerList = new ArrayList<>();
		List<EnHearing> listProblem = enHearingMapper.selectEnHearing(json);
		Map<String,List<EnHearing>> hearingMap = listProblem.stream().collect(Collectors.groupingBy(EnHearing::getHearingSection));
		List<EnHearing> listHearing = enHearingMapper.selectEnHearingByList(json).getList();
		Map<String,List<EnHearing>> hearingIdMap = listHearing.stream().filter(e->!StrUtile.isEmpty(e.getUpHearingId())).collect(Collectors.groupingBy(EnHearing::getUpHearingId));

		List<JSONObject> listData = new ArrayList<>();
		// 四级  新闻3  对话2  段落3 六级 对话2 段落2 讲座3
		if("1".equals(json.getString("problemDifficulty"))){
			for (Map.Entry<String,List<EnHearing>> e:hearingMap.entrySet()) {
				List<EnHearing> hs = new ArrayList<>();
				List<EnAnswer> answers = new ArrayList<>();
				JSONObject j = new JSONObject();
				j.put("hearingSection",e.getKey());
				if(e.getKey().contains("A")){ // SectionA 为新闻题
					if(e.getValue().size() < 3){
						throw new SysException("题库中未找到合适的试题,请联系老师!");
					}
					List<EnHearing> list = e.getValue().stream().sorted(Comparator.comparing(EnHearing::getHearingId)).collect(Collectors.toList());
					EnHearing h1 = list.get(0); // 第一篇新闻有两道题
					saveProblem(h1.getProblemList(),2,answers);
					hs.addAll(hearingIdMap.get(h1.getUpHearingId()));
					EnHearing h2 = list.get(1); // 第二篇新闻有两道题
					saveProblem(h2.getProblemList(),2,answers);
					hs.addAll(hearingIdMap.get(h2.getUpHearingId()));
					EnHearing h3 = list.get(2); // 第三篇新闻有三道题
					saveProblem(h3.getProblemList(),3,answers);
					hs.addAll(hearingIdMap.get(h3.getUpHearingId()));
				}
				if(e.getKey().contains("B")) { // SectionB 为对话题
					Map<String,List<EnHearing>> hearingB = e.getValue().stream().collect(Collectors.groupingBy(EnHearing::getUpHearingId));
					if(hearingB.size() < 2){ // 最少两篇对话
						throw new SysException("题库中未找到合适的试题,请联系老师!");
					}
					for (Map.Entry<String,List<EnHearing>> e1:hearingB.entrySet()) {
						saveProblem(e1.getValue().get(0).getProblemList(),4,answers); // 对话每篇4道题
						hs.addAll(hearingIdMap.get(e1.getKey()));
					}
				}
				if(e.getKey().contains("C")){ // SectionC 为段落题
					if(e.getValue().size() < 3){
						throw new SysException("题库中未找到合适的试题,请联系老师!");
					}
					List<EnHearing> list = e.getValue().stream().sorted(Comparator.comparing(EnHearing::getHearingId)).collect(Collectors.toList());
					EnHearing h1 = list.get(0); // 第一段有3道题
					saveProblem(h1.getProblemList(),3,answers);
					hs.addAll(hearingIdMap.get(h1.getUpHearingId()));
					EnHearing h2 = list.get(1); // 第二段有3道题
					saveProblem(h2.getProblemList(),3,answers);
					hs.addAll(hearingIdMap.get(h2.getUpHearingId()));
					EnHearing h3 = list.get(2); // 第三段有4道题
					saveProblem(h3.getProblemList(),4,answers);
					hs.addAll(hearingIdMap.get(h3.getUpHearingId()));
				}
				j.put("hearingList",hs.stream().sorted(Comparator.comparing(EnHearing::getHearingSection).thenComparing(EnHearing::getHearingId, Comparator.naturalOrder())).collect(Collectors.toList()));
				j.put("problemList",answers.stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList()));
				listData.add(j);
				answerList.addAll(answers);
			}
		}else {
			for (Map.Entry<String,List<EnHearing>> e:hearingMap.entrySet()) {
				List<EnHearing> hs = new ArrayList<>();
				List<EnAnswer> answers = new ArrayList<>();
				JSONObject j = new JSONObject();
				j.put("hearingSection",e.getKey());
				if(e.getKey().contains("A")){ // SectionA 对话

					Map<String,List<EnHearing>> hearingA = e.getValue().stream().collect(Collectors.groupingBy(EnHearing::getUpHearingId));
					if(hearingA.size() < 2){ // 最少两篇对话
						throw new SysException("题库中未找到合适的试题,请联系老师!");
					}
					for (Map.Entry<String,List<EnHearing>> e1:hearingA.entrySet()) {
						saveProblem(e1.getValue().get(0).getProblemList(),4,answers); // 对话每篇4道题
						hs.addAll(hearingIdMap.get(e1.getKey()));
					}
				}
				if(e.getKey().contains("B")) { // SectionB 为段落
					if(e.getValue().size() < 2){
						throw new SysException("题库中未找到合适的试题,请联系老师!");
					}
					List<EnHearing> list = e.getValue().stream().sorted(Comparator.comparing(EnHearing::getHearingId)).collect(Collectors.toList());
					EnHearing h1 = list.get(0); // 第一篇新闻有两道题
					saveProblem(h1.getProblemList(),3,answers);
					hs.addAll(hearingIdMap.get(h1.getUpHearingId()));
					EnHearing h2 = list.get(1); // 第二篇新闻有两道题
					saveProblem(h2.getProblemList(),4,answers);
					hs.addAll(hearingIdMap.get(h2.getUpHearingId()));
				}
				if(e.getKey().contains("C")){ // SectionC 为讲话
					Map<String,List<EnHearing>> hearingC = e.getValue().stream().collect(Collectors.groupingBy(EnHearing::getUpHearingId));
					if(hearingC.size() < 3){
						throw new SysException("题库中未找到合适的试题,请联系老师!");
					}
					List<String> keys = new ArrayList<>(hearingC.keySet()).stream().sorted(Comparator.comparing(String::toString)).collect(Collectors.toList());
					for (int i = 0; i < keys.size(); i++) {
						if(i==3){
							break;
						}
						if(i > 0){
							saveProblem(hearingC.get(keys.get(i)).get(0).getProblemList(),3,answers); // 后边每篇3道题
							hs.addAll(hearingIdMap.get(keys.get(i)));
							continue;
						}
						saveProblem(hearingC.get(keys.get(i)).get(0).getProblemList(),4,answers); // 第一篇4道题
						hs.addAll(hearingIdMap.get(keys.get(i)));
					}
				}
				j.put("hearingList",hs.stream().sorted(Comparator.comparing(EnHearing::getHearingSection).thenComparing(EnHearing::getHearingId, Comparator.naturalOrder())).collect(Collectors.toList()));
				j.put("problemList",answers.stream().sorted(Comparator.comparing(EnAnswer::getProblemId)).collect(Collectors.toList()));
				listData.add(j);
				answerList.addAll(answers);
			}
		}
		if(answerList.isEmpty()){
			throw new SysException("题库中未找到合适的试题,请联系老师!");
		}
		for (EnAnswer answer:answerList) {
			answer.setScoreId(score.getScoreId());
		}
		score.setProblemDate(answerList.get(0).getProblemDate());
		enAnswerMapper.insertAllEnAnswer(answerList);
		enScoreMapper.insertEnScore(score);

		listData = listData.stream().sorted(Comparator.comparing(j -> j.getString("hearingSection"))).collect(Collectors.toList());
		return listData;
	}


	public void saveProblem(List<EnAnswer> problemList,int s,List<EnAnswer> answerSet){
		try {
			Collections.shuffle(problemList);
			Map<String,List<EnAnswer>> pp = problemList.stream().collect(Collectors.groupingBy(EnAnswer::getProblemType));
			List<List<EnAnswer>> pm = new ArrayList<>();
			for (Map.Entry<String,List<EnAnswer>> pm1:pp.entrySet()) {
				pm.add(pm1.getValue());
			}
			for (int i = 0,j=0; j < s;i++) {
				answerSet.add(pm.get(0).get(i));
				j++;
				if(j >= s){
					break;
				}
				answerSet.add(pm.get(1).get(i));
				j++;
			}
		}catch (Exception e){
			throw new SysException("试题加载失败,请联系老师检查题库!");
		}
	}
}